﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

namespace Mimoza.PluginLayer
{
    /// <summary>
    ///  Plugin manager.
    /// </summary>    
    public class PluginManager
    {
        List<IConfigPlugin> m_plugins = new List<IConfigPlugin>();

        /// <summary>
        /// Initialize plugin manager from XML files in application
        /// directory.
        /// </summary>
        public void Init()
        {
            Init("");
        }

        /// <summary>
        /// Initialize plugin manager from XML files in application
        /// directory + sub directory.
        /// </summary>
        public void Init(string subDirectory)
        {
            string path = Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
            path = Path.GetDirectoryName(path);
            if (subDirectory != null && subDirectory != "")
            {
                path += ("/" + subDirectory);
            }

            Common.Logger.Log.Trace(
                "Initializing PluginManager from {0} directory",
                path);

            foreach (string file in Directory.GetFiles(path, "*.xml"))
            {
                PluginLoader loader = new PluginLoader();
                loader.Init(file);
                m_plugins.AddRange(loader.ConfigPlugins);
            }

            Common.Logger.Log.Trace(
                "Finished initialization of PluginManager. Plugins count - {0}",
                m_plugins.Count);
        }

        public List<IConfigPlugin> Plugins
        {
            get { return m_plugins; }
        }

        public IConfigPlugin GetConfigPlugin(string pluginID)
        {
            foreach (IConfigPlugin plugin in this.Plugins)
            {
                string identity = plugin.Identity;

                if (Common.ArrayToString.IsSeparatedString(identity))
                {
                    string[] ids = Common.ArrayToString.FromString(plugin.Identity);
                    if (Array.IndexOf(ids, pluginID) >= 0) return plugin;
                }
                else
                {
                    if (plugin.Identity == pluginID) return plugin;
                }
            }

            return null;
        }
    }
}
